package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.mapper.ForumMapper;
import com.example.mapper.ForumTopicMapper;
import com.example.pojo.Forum;
import com.example.pojo.ForumReply;
import com.example.mapper.ForumReplyMapper;
import com.example.pojo.ForumTopic;
import com.example.pojo.PageBean;
import com.example.service.ForumReplyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author testjava
 * @since 2022-08-20
 */
@Service
public class ForumReplyServiceImpl extends ServiceImpl<ForumReplyMapper, ForumReply> implements ForumReplyService {
    @Autowired
    private ForumReplyMapper forumReplyMapper;
    @Autowired
    private ForumTopicMapper forumTopicMapper;
    @Autowired
    private ForumMapper forumMapper;

    @Override
    public List<ForumReply> getReplyByTid(Integer tid) {
        return forumReplyMapper.selectByTid(tid);
    }

    @Override
    public PageBean<ForumReply> getReplyByPage(Integer currentPage, Integer pageSize, Integer tid) {
        currentPage = (currentPage - 1) * pageSize;
        //获取数据
        List<ForumReply> replyList = forumReplyMapper.getPage(currentPage, pageSize, tid);
        //获取总数
        LambdaQueryWrapper<ForumReply> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(tid != null, ForumReply::getTopicId, tid);
        int count = count(wrapper);

        return new PageBean<>(currentPage,pageSize,count,replyList);
    }

    /**
     * 添加回复
     * @param forumReply
     * @param replyCount
     * @param forumId
     * @param articleCount
     * @return
     */
    @Override
    public boolean addReply(ForumReply forumReply, Integer replyCount, Integer forumId, Integer articleCount) {
        //添加回复
        boolean save = this.save(forumReply);
        //修改主题的replyCount，lastReplyId
        Integer lastReplyId = forumReply.getRid();
        ForumTopic forumTopic = new ForumTopic();
        forumTopic.setTid(forumReply.getTopicId());
        forumTopic.setReplyCount(replyCount);
        forumTopic.setLastReplyId(lastReplyId);

        int updateTopic = forumTopicMapper.updateById(forumTopic);
        //修改论坛的articleCount
        Forum forum = new Forum();
        forum.setFid(forumId);
        forum.setArticleCount(articleCount);

        int updateForum = forumMapper.updateById(forum);

        return save && updateTopic == 1 && updateForum == 1;
    }
}
